/*
 * @lc app=leetcode.cn id=2048 lang=typescript
 *
 * [2048] 下一个更大的数值平衡数
 */

// @lc code=start
function nextBeautifulNumber(n: number): number {
  if (n === 0) return 1;
  // 得到当前数字的位数
  const digit = Math.floor(Math.log10(n)) + 1;
  // 存储所有平衡数
  const arr: number[] = [];

  // 将位数拆分成合适的数字
  // 比如5位数拆成[1,4],[2,3]等
  const getBlanceNumber = (digit: number, idx: number, buff: number[] = []) => {
    if (digit === 0) {
      const temp = [];
      for (const x of buff) {
        for (let k = 0; k < x; k++) {
          temp.push(x);
        }
      }
      getALLPermutation(0, temp);
      return;
    }
    for (let i = idx; i <= digit; i++) {
      if (i === digit || digit - i > i) {
        buff.push(i);
        getBlanceNumber(digit - i, i + 1, buff);
        buff.pop();
      }
    }
  };
  // 平衡数的全排列
  const getALLPermutation = (i: number, buff: number[]) => {
    if (i === buff.length) {
      arr.push(Number(buff.join('')));
    }
    for (let j = i; j < buff.length; j++) {
      [buff[i], buff[j]] = [buff[j], buff[i]];
      getALLPermutation(i + 1, buff);
      [buff[i], buff[j]] = [buff[j], buff[i]];
    }
  };

  getBlanceNumber(digit, 1);
  getBlanceNumber(digit + 1, 1);

  let ans = Number.MAX_SAFE_INTEGER;
  for (const x of arr) {
    if (x > n) {
      ans = Math.min(ans, x);
    }
  }

  return ans;
}
// @lc code=end
